from aiogram import Router, F
from aiogram.filters import Command, StateFilter
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import StatesGroup, State
from aiogram.types import Message, ReplyKeyboardRemove

from keyboards.set_menu import just_keyboard, cancel_keyboard

from db.PGConnector import PGFamilyUser
from .utils import try_except_decorator

router = Router()


class BotState(StatesGroup):
    choosing_family = State()

@router.message(StateFilter(None), F.text == "Выбрать семью")
async def cmd_choose(message: Message, state: FSMContext):
    user_id = message.chat.id

    pg_family_user = PGFamilyUser()
    families_dict = pg_family_user.get_families_info(user_id)
    families_info = 'На данный момент вы состоите в следующих семьях:\n'

    for family_id, family_name in families_dict.items():
        families_info += f"\nid = {family_id}, family_name = {family_name}\n --------------------------------------- \n"

    await message.answer(text=f"{families_info}\nНапишите id семьи, которую вы хотите активировать.",
                         reply_markup=cancel_keyboard())
    await state.set_state(BotState.choosing_family)
    

@try_except_decorator
@router.message(BotState.choosing_family)
async def chosen_family(message: Message, state: FSMContext):
    await state.update_data(family_id=message.text)

    active_family_id = await state.get_data()
    active_family_id = active_family_id['family_id'].strip()

    user_id = message.chat.id

    pg_family_user = PGFamilyUser()
    choosed_family = pg_family_user.make_family_active(active_family_id, user_id)

    if choosed_family:
        await message.answer(text=f"Cемья активирована.",
                             reply_markup=just_keyboard())
    else:
        await message.answer(text=f"Некорректный id семьи.",
                             reply_markup=just_keyboard())
    await state.clear()





